<template>
  <div>
    <el-dialog :title="`${form.prjchkId ? '修改' : '添加'}交付得分`" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="1200px" @closed="close">
      <div class="form-score" v-loading="formLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="10" style="display: flex;flex-wrap: wrap;">
            <el-col :span="8">
              <el-form-item label="项目" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择项目" filterable clearable style="width: 100%" class="input-width" :disabled="!!form.prjchkId || form.rdcType == CQ_EVAL_RDC_TYPE.DEPT1" @change="onChangeProject">
                  <el-option v-for="project in formProjectOptions" :key="project.fid" :label="project.cflastname" :value="project.fid" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查单位" prop="rdcType">
                <el-radio-group v-model="form.rdcType" class="input-width" disabled>
                  <el-radio v-for="dict in dict.type.cq_random_type" :key="dict.value" :label="dict.value">{{ dict.label }} </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交付类型" prop="deliveryTypes">
                <el-select v-model="form.deliveryTypes" placeholder="交付类型" class="input-width" :disabled="!!form.prjchkId || form.rdcType == CQ_EVAL_RDC_TYPE.DEPT1" @change="deliveryChange">
                  <el-option v-for="dict in dict.type.cq_eval_delivery_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查日期" prop="checkDate">
                <el-date-picker v-model="form.checkDate" value-format="yyyy-MM-dd" type="date" class="input-width" placeholder="选择日期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查人员" prop="principalId">
                <el-select v-model="form.principalId" placeholder="请选择检查人员" filterable :loading="principalLoading" style="width: 100%" @change="onChangePrincipalId">
                  <el-option v-for="item in principalList" :key="item.fid" :label="item.nickName" :value="item.fid" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="施工单位" prop="constructionId" style="height: 36px">
                <el-select v-model="form.constructionId" class="optimized-select" placeholder="请选择施工单位" filterable multiple collapse-tags clearable :loading="constructionLoading" @change="onChangeConstructionId">
                  <el-option v-for="item in constructionList" :key="item.constructionId" :label="item.constructionName" :value="item.constructionId" />
                  <el-option value="" @click.native="showEditRdcConstruction = true">
                    <el-button size="mini" type="text" icon="el-icon-plus">添加施工单位</el-button>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目(检查口径)" prop="inpectionCaliber">
                <el-input v-model.trim="form.inpectionCaliber" placeholder="请输入检查球号对应名称" :maxlength="255" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="施工单位负责人" prop="constructionUser">
                <el-input v-model.trim="form.constructionUser" placeholder="请输入施工单位负责人" :maxlength="255" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目总" prop="xmzName">
                <el-input class="fake-selector input-width" readonly v-model="form.xmzName" auto-complete="off" placeholder="请选择项目总" @click.native="openSelectUser('xmzId', 'xmzName', true)">
                  <i slot="append" class="el-icon-arrow-down" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目经理" prop="xmjlName">
                <el-input class="fake-selector input-width" readonly v-model="form.xmjlName" auto-complete="off" placeholder="请选择项目经理" @click.native="openSelectUser('xmjlId', 'xmjlName', true)">
                  <i slot="append" class="el-icon-arrow-down" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目工程负责人" prop="xmPrincipalName">
                <el-input class="fake-selector" readonly v-model="form.xmPrincipalName" placeholder="请选择项目工程负责人" @click.native="openSelectUser('xmPrincipalId', 'xmPrincipalName', true)">
                  <i slot="append" class="el-icon-arrow-down" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="集群分管领导" prop="colonyName">
                <el-input class="fake-selector input-width" readonly v-model="form.colonyName" auto-complete="off" placeholder="请选择集群分管领导" @click.native="openSelectUser('colonyId', 'colonyName', true)">
                  <i slot="append" class="el-icon-arrow-down" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事业部分管领导" prop="businessName">
                <el-input class="fake-selector input-width" readonly v-model="form.businessName" auto-complete="off" placeholder="请选择事业部分管领导" @click.native="openSelectUser('businessId', 'businessName', true)">
                  <i slot="append" class="el-icon-arrow-down" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="描述">
                <el-input v-model.trim="form.description" placeholder="请输入描述" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-popover
            placement="right"
            width="700"
            trigger="hover"
            v-if="form.rdcType == CQ_EVAL_RDC_TYPE.DEPT1"
          >
            <div class="relation-prochk">
              <div class="row">
                <span>项目:</span>
                <span class="value">{{ relationObj.projectName }}</span>
              </div>
              <div class="row">
                <span>检查单位:</span><span class="value">{{ relationObj.rdcType | dictFilter(dict.type.cq_random_type) }}</span>
              </div>
              <div class="row">
                <span>类型:</span><span class="value">{{ relationObj.deliveryTypes | dictFilter(dict.type.cq_eval_delivery_type) }}</span>
              </div>
              <div class="row">
                <span>检查时间:</span><span class="value">{{ relationObj.checkDate }}</span>
              </div>
              <div style="width: 100%">
                <DeliveryScoreDisplay :value="relationObj" :cfg="cfg" show-throw-term />
              </div>
              <!--<div v-if="relationObj.scores" class="score-wrap">
                <div v-for="(score, index) in relationObj.scores" :key="'score' + index" class="row-score">
                  <span>
                    <span>{{ score.chkitemName }}:</span>
                    <div class="delivery-type" v-if="relationObj.deliveryTypes === deliveryType.JZMP">{{ score.deliveryType | dictFilter(dict.type.cq_eval_delivery_type) }}</div>
                  </span>
                  <span class="value">{{ score.scoreInput }}</span>
                  <span class="value" :class="score.scoreResult">{{ score.scoreResult | dictFilter(dict.type.cq_eval_result_enum) }}</span>
                </div>
              </div>-->
            </div>
            <span slot="reference" class="relation-item">
              <i class="el-icon-info" />
              <span>集群信息</span>
            </span>
          </el-popover>
          <!--<el-form-item>
            <el-select v-model="form.relationPrjchkId" placeholder="请选择关联集群" class="input-width" @change="relationChange">
              <el-option v-for="Prjchk in relationLIst" :key="Prjchk.prjchkId" :label="Prjchk.phaseName" :value="Prjchk.prjchkId" />
            </el-select>
          </el-form-item>-->
          <el-divider style="margin-top: 0px;">检查项录入</el-divider>
          <!--配置为选项时-->
          <el-popover v-if="query.inputMode === CQ_EVAL_INPUT_MODE.OPTION" placement="right" width="200" trigger="click" v-model="showOptList">
            <el-button slot="reference" size="mini" type="primary" @click="selected = []" style="margin-bottom: 10px;">添加检查项</el-button>
            <el-empty :image-size="50" v-if="!allCheckItemList.length" />
            <div class="opt-list-wrap" v-else>
              <div class="opt-list">
                <div
                  class="opt-item ellipsis"
                  v-for="item in allCheckItemList"
                  :key="item.chkitemCode"
                  :title="item.chkitemName"
                  :class="{
                    selected: selected.includes(item.chkitemCode),
                    disabled: selectedCodes.includes(item.chkitemCode)
                  }"
                  @click="selectItem(item)"
                >
                  {{ item.chkitemName }}
                </div>
              </div>
              <div class="btn">
                <el-button size="mini" type="primary" :disabled="!selected.length" @click="addItem">添加 {{ selected.length }}/{{ allCheckItemList.length - selectedCodes.length }}</el-button>
              </div>
            </div>
          </el-popover>
          <!--全部甩项-->
          <el-checkbox v-model="allNoCheck" style="margin: 0 0 10px 10px;">全部甩项</el-checkbox>
          <!--<el-row :gutter="10">
            <el-col :span="6" v-for="(item, index) in checkItemList" :key="'form' + item.chkitemId">
              <div v-if="shareItemCode.some(shareCode => shareCode === item.chkitemCode)" class="item" :style="{height: colHeight}">
                <div class="lable-title">
                  <span><span style="color: red;">*</span>{{ item.chkitemName }}</span>
                  <i v-if="query.inputMode==CQ_EVAL_INPUT_MODE.OPTION" class="el-icon-close btn-remove pointer" @click="removeCheckItem(index)" />
                  <el-checkbox v-else v-model="item.noCheck" @change="noCheckChange(item)">
                    <span style="font-size: 12px;">
                      甩项
                    </span>
                  </el-checkbox>
                </div>
                <div class="custom-form-item">
                  &lt;!&ndash; <el-input v-if="item.dataType === 'number'" v-model.trim="item.scoreNum" placeholder="分数" :maxlength="50" class="score-value" @input="forceUpdate" @change="scoreChange($event, item, 'scoreInput')">
                    <template slot="append">分</template>
                  </el-input>&ndash;&gt;
                  <el-select v-model="item.scoreInput" placeholder="等级" size="small" class="score-level" @change="levelChange($event, item, 'scoreResult')" :disabled="CQ_EVAL_RESULT.THROWTERM == item.scoreResult" default-first-option filterable>
                    <el-option v-for="dict in item.dicts" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                  &lt;!&ndash;<span v-if="CQ_EVAL_RESULT.THROWTERM != item.scoreResult" class="score-result" :class="[ item.scoreResult ]">{{ item.scoreResult | dictFilter(dict.type.cq_eval_result_enum) }}</span>&ndash;&gt;
                  <el-dropdown @command="resultChange($event, item, 'scoreResult')" v-if="CQ_EVAL_RESULT.THROWTERM != item.scoreResult" trigger="click" class="score-result">
                    <dict-tag :options="dict.type.cq_eval_result" :value="item.scoreResult" />
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="dictItem in dict.type.cq_eval_result" :key="'scoreResult'+dictItem.value" :command="dictItem.value">{{ dictItem.label }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>
              <div v-else class="item" :style="{height: colHeight}">
                <div class="lable-title">
                  <span><span style="color: red;">*</span>{{ item.chkitemName }}</span>
                  <el-popconfirm v-if="query.inputMode==CQ_EVAL_INPUT_MODE.OPTION" title="移除此检查项？" confirm-button-text="移除" @confirm="removeCheckItem(index)">
                    <i class="el-icon-close btn-remove pointer" />
                  </el-popconfirm>
                  <el-checkbox v-else v-model="item.noCheck" @change="noCheckChange(item)">
                    <span style="font-size: 12px;">
                      甩项
                    </span>
                  </el-checkbox>
                </div>
                <div class="custom-form-item" v-show="form.deliveryTypes.includes(deliveryType.JZ)">
                  <div class="label-select">
                    <div :style="{ width: labelWidth}">{{ label.jz }}</div>
                    &lt;!&ndash;<el-input v-if="item.dataType === 'number'" v-model.trim="item.hardcover_scoreNum" placeholder="分数" :maxlength="50" class="score-value" @input="forceUpdate" @change="scoreChange($event, item, 'hardcover_scoreInput')">
                      <template slot="append">分</template>
                    </el-input>&ndash;&gt;
                    <el-select v-model="item.hardcover_scoreInput" placeholder="等级" size="small" class="score-level" @change="levelChange($event, item, 'hardcover_scoreResult')" :disabled="CQ_EVAL_RESULT.THROWTERM == item.hardcover_scoreResult" default-first-option filterable>
                      <el-option v-for="dict in item.dicts" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </div>
                  &lt;!&ndash;<span v-if="CQ_EVAL_RESULT.THROWTERM != item.hardcover_scoreResult" class="score-result" :class="[ item.hardcover_scoreResult ]">{{ item.hardcover_scoreResult | dictFilter(dict.type.cq_eval_result_enum) }}</span>&ndash;&gt;
                  <el-dropdown @command="resultChange($event, item, 'hardcover_scoreResult')" v-if="CQ_EVAL_RESULT.THROWTERM != item.hardcover_scoreResult" trigger="click" class="score-result">
                    <dict-tag :options="dict.type.cq_eval_result" :value="item.hardcover_scoreResult" />
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="dictItem in dict.type.cq_eval_result" :key="'hardcover_scoreResult'+dictItem.value" :command="dictItem.value">{{ dictItem.label }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <div class="custom-form-item" v-show="form.deliveryTypes.includes(deliveryType.MP)">
                  <div class="label-select">
                    <div :style="{ width: labelWidth}">{{ label.mp }}</div>
                    &lt;!&ndash;<el-input v-if="item.dataType === 'number'" v-model.trim="item.workblank_scoreNum" placeholder="分数" :maxlength="50" class="score-value" @input="forceUpdate" @change="scoreChange($event, item, 'workblank_scoreInput')">
                      <template slot="append">分</template>
                    </el-input>&ndash;&gt;
                    <el-select v-model="item.workblank_scoreInput" placeholder="等级" size="small" class="score-level" @change="levelChange($event, item, 'workblank_scoreResult')" :disabled="CQ_EVAL_RESULT.THROWTERM == item.workblank_scoreResult" default-first-option filterable>
                      <el-option v-for="dict in item.dicts" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </div>
                  &lt;!&ndash;<span v-if="CQ_EVAL_RESULT.THROWTERM != item.workblank_scoreResult" class="score-result" :class="[ item.workblank_scoreResult ]">{{ item.workblank_scoreResult | dictFilter(dict.type.cq_eval_result_enum) }}</span>&ndash;&gt;
                  <el-dropdown @command="resultChange($event, item, 'workblank_scoreResult')" v-if="CQ_EVAL_RESULT.THROWTERM != item.workblank_scoreResult" trigger="click" class="score-result">
                    <dict-tag :options="dict.type.cq_eval_result" :value="item.workblank_scoreResult" />
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="dictItem in dict.type.cq_eval_result" :key="'workblank_scoreResult'+dictItem.value" :command="dictItem.value">{{ dictItem.label }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>
            </el-col>
          </el-row>-->
          <div style="margin-left: 10px">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="毛胚" name="first"></el-tab-pane>
              <el-tab-pane label="精装" name="second"></el-tab-pane>
            </el-tabs>
          </div>
          <div class="list">
            <div class="item" v-for="item in checkItemList" :key="item.chkitemCode">
              <number-score v-model="item.data" :cfg="item" />
            </div>
          </div>
          <el-divider />
          <el-form-item style="margin-top: 10px;" label-width="0">
            <el-upload
              ref="upload"
              :action="FILE_MULTI_UPLOAD_URL"
              :data="{ type: 'qcMoudle' }"
              :show-file-list="false"
              name="files"
              :disabled="uploading"
              accept=".doc,.docx,.xls,.xlsx,.pdf"
              :before-upload="beforeUpload"
              :on-error="onUploadError"
              :on-success="onUploadSuccess"
            >
              <el-button :loading="uploading" slot="default" size="small" type="primary" icon="el-icon-plus">选取文件</el-button>
            </el-upload>
            <el-row :gutter="10" v-loading="fileLoading" class="file-list">
              <el-col :span="8" v-for="file in fileList" :key="file.id">
                <div class="file-item">
                  <div @click="onPreview(file)" class="file-name">
                    <i class="el-icon-document" />
                    <span class="name">{{ file.name }}</span>
                  </div>
                  <i class="el-icon-close" @click="handleRemove(file)" />
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div class="operate-btn">
        <el-button type="primary" :loading="btnLoading" @click="submitForm">确 定</el-button>
        <el-button :disabled="btnLoading" @click="close">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择人员 -->
    <select-user-dialog :show.sync="showSelectUserVisible" :selected="selectedUser" :multi="selectUserOption.multi" :max-num="5" @select="selectUserCallback" />
    <!-- 编辑施工单位 -->
    <EditRdcConstruction ref="EditRdcConstruction" v-model="showEditRdcConstruction" @ok="getConstructionList" />
    <SimilarDataConfirm ref="SimilarDataConfirm" @confirm="submitForm({ isRepeatEntry: 'allow' })" />
  </div>
</template>
<script>
import store from '@/store'
import auth from '@/plugins/auth'
import { getUserByRoleKey } from '@/api/system/user'
import NumberScore from '../chkitemScore/NumberScore'
// 添加或修改阶段对话框
import { saveScores, getProTradeType, listProPhase } from '@/api/checkScore/projectScore'
import SelectUserDialog from '@/views/components/SelectUserDialog.vue'
import { FILE_MULTI_UPLOAD_URL, downloadFile } from '@/api/common'
import { matchingRule } from '../chkitemScore/common'
import { shareItemCode, deliveryType, CQ_EVAL_INPUT_MODE, CQ_EVAL_RDC_TYPE, CQ_EVAL_RESULT_ENUM as CQ_EVAL_RESULT } from '@/utils/baseData'
import { listRdcConstruction } from '@/api/qualityManage/cq'
import EditRdcConstruction from '@/views/cq/components/EditRdcConstruction'
import DeliveryScoreDisplay from './DeliveryScoreDisplay'
import SimilarDataConfirm from './SimilarDataConfirm'
const formInit = {
  prjchkId: '', // 主键
  versionCode: '',
  chkitemCode: '',
  projectId: '',
  landparcelId: '', // 宗地ID
  fileIds: [],
  specialRule: '',
  deliveryTypes: '', // 交付类型
  inpectionCaliber: '', // 检查口径
  checkDate: new Date(),
  rdcType: '', // 检查单位
  relationPrjchkId: '', // 关联
  constructionId: [], // 施工单位
  constructionName: '',
  constructionUser: '', // 施工单位负责人
  principalUserName: '', // 检查人员
  principalId: '',
  description: '',
  xmzId: '',
  xmzName: '',
  xmPrincipalId: '',
  xmPrincipalName: '',
  xmjlId: '',
  xmjlName: '',
  colonyId: '',
  colonyName: '',
  businessId: '',
  businessName: ''
}
export default {
  filters: {
    dictFilter (val, list) {
      let str = ''
      for (let i = 0; i < list.length; i++) {
        if (val === list[i].value) {
          str = list[i].label
        }
      }
      return str
    }
  },
  components: {NumberScore, SelectUserDialog, EditRdcConstruction, DeliveryScoreDisplay, SimilarDataConfirm },
  props: {
    cfg: { type: Object, default: () => ({}) }
  },
  dicts: ['cq_random_type', 'cq_eval_delivery_type', 'cq_eval_abc', 'cq_eval_result_enum', 'cq_eval_result', 'cq_eval_valid'],
  data() {
    return {
      FILE_MULTI_UPLOAD_URL,
      CQ_EVAL_INPUT_MODE,
      CQ_EVAL_RDC_TYPE,
      CQ_EVAL_RESULT,
      uploading: false,
      query: {},
      shareItemCode: shareItemCode,
      deliveryType: deliveryType,
      fileList: [],
      fileLoading: false,
      previewSrcList: [],
      previewSrc: '',
      show: false,
      primaryKey: 'typeId',
      form: {...formInit},
      relationLIst: [],
      relationObj: {},
      checkItemList: [],
      allCheckItemList: [],
      selected: [],
      showOptList: false,
      specialTypes: [],
      btnLoading: false,
      constructionLoading: false,
      constructionList: [], // 施工单位
      showEditRdcConstruction: false, // 添加施工单位的弹窗
      gradeOptions: [
        {level: 'A'},
        {level: 'B'},
        {level: 'C'}
      ],
      formProjectOptions: [],
      formLoading: false,
      colHeight: '90px',
      labelWidth: '0',
      label: {
        mp: '',
        jz: ''
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目' }],
        rdcType: [{ required: true, message: '请选择检查单位' }],
        deliveryTypes: [{ required: true, message: '请选择检查单位' }],
        checkDate: [{ required: true, message: '请选择日期' }]
      },
      removeItemList: [],
      // 选择用户窗口
      showSelectUserVisible: false,
      selectUserOption: { idField: '', nameField: '', multi: false },
      selectedUser: [],
      allNoCheck: false,
      principalList: [],
      principalLoading: false,
      activeName: 'first'
    }
  },
  computed: {
    selectedCodes() {
      const list = this.checkItemList || []
      return list.map(i => i.chkitemCode)
    }
  },
  watch: {
    allNoCheck(val) {
      this.checkItemList.forEach(item => {
        item.noCheck = val
        this.noCheckChange(item)
      })
    }
  },
  created() {
  },
  methods: {
    // 获取检查人员
    async getPrincipalList() {
      const userFid = store.getters.user?.fid
      const { form } = this
      // const { projectId } = this.form
      // if (!projectId) return (this.principalList = [])

      // GCCJRY 工程抽检人员
      // const opt = { roleKey: 'GCCJRY', projectId }
      const opt = { roleKey: 'GCCJRY' }
      this.principalLoading = true
      const res = await getUserByRoleKey(opt).catch(() => false)
      this.principalLoading = false
      if (res === false) return (this.principalList = [])

      const data = res.data || []
      this.principalList = data

      // 新增时，若登录用户是抽检人员，自动填入
      if (form.prjchkId || form.principalId || !auth.hasRole('GCCJRY') || !userFid) return
      const item = data.find(i => i.fid === userFid)
      if (!item) return
      form.principalId = item.fid
      form.principalUserName = item.nickName
    },
    // 检查人员改变时，手动赋值 principalUserName
    onChangePrincipalId(id) {
      if (!id) return (this.form.principalUserName = '')
      const list = this.principalList || []
      const item = list.find(i => i.fid === id)
      this.form.principalUserName = item?.nickName || ''
    },
    // 获取施工单位
    async getConstructionList() {
      this.constructionLoading = true
      const res = await listRdcConstruction().catch(() => false)
      this.constructionLoading = false
      if (res === false) return
      this.constructionList = res.data || []
    },
    // 施工单位改变时，手动赋值 constructionName
    onChangeConstructionId(ids) {
      if (!ids) return (this.form.constructionName = '')
      const list = this.constructionList || []
      const names = []
      ids.forEach(id => {
        const item = list.find(i => i.constructionId === id)
        if (item && item.constructionName) {
          names.push(item.constructionName)
        }
      })
      this.form.constructionName = names.join(',')
    },
    // 打开选择用户
    openSelectUser(idField, nameField, multi) {
      this.selectUserOption = { idField, nameField, multi: !!multi }
      let selectedUser = []
      const idValue = this.form[idField] || ''
      const nameValue = this.form[nameField] || ''
      const ids = idValue ? idValue.split(',') : []
      const names = nameValue ? nameValue.split(',') : []
      if (ids.length && names.length) {
        selectedUser = ids.map((id, index) => ({ value: id, label: names[index] }))
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    // 选择用户回调
    selectUserCallback(selection) {
      const { idField, nameField } = this.selectUserOption
      this.form[idField] = selection.map(i => i.value).join(',')
      this.form[nameField] = selection.map(i => i.label).join(',')
    },
    noCheckChange(item) {
      if (item.noCheck) {
        item.scoreNum = null
        item.scoreInput = ''
        item.hardcover_scoreNum = null
        item.hardcover_scoreInput = ''
        item.workblank_scoreNum = null
        item.workblank_scoreInput = ''
        item.scoreResult = CQ_EVAL_RESULT.THROWTERM
        item.hardcover_scoreResult = CQ_EVAL_RESULT.THROWTERM
        item.workblank_scoreResult = CQ_EVAL_RESULT.THROWTERM
      } else {
        item.scoreResult = ''
        item.hardcover_scoreResult = ''
        item.workblank_scoreResult = ''
      }
      this.forceUpdate()
    },
    selectItem(item) {
      const { selected } = this
      const code = item.chkitemCode
      const index = selected.findIndex(i => i === code)
      if (index > -1) selected.splice(index, 1)
      else selected.push(code)
    },
    addItem() {
      const { allCheckItemList, selected, checkItemList } = this
      this.showOptList = false
      // const isExist = checkItemList.find(i => i.chkitemCode === selected)
      // if (isExist) return this.$message('该检查项已存在')

      const arr = allCheckItemList.filter(i => selected.includes(i.chkitemCode))
      checkItemList.push(...arr)
      this.selected = []
    },
    removeCheckItem(index) {
      this.checkItemList[index].isDelete = 1
      this.removeItemList.push(this.checkItemList[index])
      this.checkItemList.splice(index, 1)
    },
    // 操盘 过滤
    async tradeFilter () {
      if (this.form.projectId) {
        const response = await getProTradeType({ projectId: this.form.projectId }).catch(() => false)
        if (response.code === 200) {
          const tradeType = response.data
          if (!tradeType) {
            this.$message.warning('项目不属于操盘与非操盘')
          }
          this.checkItemList = this.checkItemList.filter(item => item.tradeType.split(',').some(trade => trade === tradeType))
        }
      }
    },
    // 获取关联评分
    getRelationScore () {
      if (!this.form.relationPrjchkId) return
      this.formLoading = true
      const params = {
        prjchkId: this.form.relationPrjchkId
      }
      listProPhase(params).then(response => {
        if (response.code === 200) {
          if (response.data.length > 0) {
            this.relationObj = response.data[0]
          }
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    // 检查单位改变
    /* rdcTypeChange() {
      if (this.form.projectId && this.form.rdcType === CQ_EVAL_RDC_TYPE.DEPT1) {
        const params = {
          projectId: this.form.projectId,
          rdcType: CQ_EVAL_RDC_TYPE.DEPT2
        }
        this.formLoading = true
        listProPhase(params).then(response => {
          if (response.code === 200) {
            this.relationLIst = response.data
            this.relationChange()
          }
        }).finally(() => {
          this.formLoading = false
        })
      }
    },*/
    // 关联得分改变
    // relationChange() {
    //   if (!this.form.relationPrjchkId || this.relationLIst.length < 1) return
    //   for (let i = 0; i < this.relationLIst.length; i++) {
    //     if (this.relationLIst[i].prjchkId === this.form.relationPrjchkId) {
    //       this.relationObj = this.relationLIst[i]
    //       this.relationObj.scores.forEach(score => {
    //         if (score.deliveryType === deliveryType.JZMP) {
    //           score.sort = 1
    //         } else {
    //           score.sort = 0
    //         }
    //       })
    //       this.relationObj.scores.sort((obj1, obj2) => {
    //         if (obj1.sort === obj2.sort) {
    //           return obj1.chkitemCode.localeCompare(obj2.chkitemCode)
    //         }
    //         return obj2.sort - obj1.sort
    //       })
    //     }
    //   }
    // },
    levelChange(level, item, key) {
      // let resultStdd = []
      // try {
      //   resultStdd = JSON.parse(item.resultStdd)
      // } catch (e) {
      //   console.log(e)
      // }
      // resultStdd.forEach(stdd => {
      //   if (stdd.level === level) {
      //     item[key] = stdd.result
      //   }
      // })
      if (item.scoreType === 'cq_eval_abc') {
        item[key] = matchingRule({rule: item.resultStdd, value: level})
      } else {
        item[key] = level
      }
      this.forceUpdate()
    },
    // 合格状态改变
    resultChange(result, item, key) {
      const type = key.split('_')[0]
      const scoreInputKey = `${type}_scoreInput`
      // 交付得分
      if (item.chkitemCode === 'GC-001-004-010' && item[scoreInputKey] !== result) {
        this.$confirm('此操作导致交付得分状态结果不一致, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          item[key] = result
          this.forceUpdate()
        })
      } else {
        item[key] = result
        this.forceUpdate()
      }
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    init (row, options) {
      const self = this
      this.formProjectOptions = options.formProjectOptions
      this.fileList = []
      this.removeItemList = []
      this.getConstructionList()
      for (const key in this.form) {
        this.form[key] = formInit[key]
      }
      this.relationObj = {}
      this.query = this.$route.query
      this.form.deliveryTypes = deliveryType.JZ
      this.form.specialRule = this.query.specialRule
      this.form.versionCode = this.query.versionCode
      this.form.chkitemCode = this.query.chkitemCode
      /* 新增检查单位类型*/
      if (options.rdcType) {
        this.form.rdcType = options.rdcType
        /*
        *  集团关联集群对象
        * */
        if (options.rdcType === CQ_EVAL_RDC_TYPE.DEPT1 && options.relationObj) {
          this.relationObj = options.relationObj
          this.form.relationPrjchkId = this.relationObj.prjchkId
          if (this.relationObj.scores && this.relationObj.scores.length > 0) {
            relationHandle()
          }
          this.form.projectId = options.relationObj.projectId
          this.form.deliveryTypes = options.relationObj.deliveryTypes
        }
      }
      if (options && options.checkItemList) {
        options.checkItemList.forEach(item => {
          item.scoreNum = null
          item.scoreInput = null
          item.hardcover_scoreNum = null
          item.hardcover_scoreInput = null
          item.workblank_scoreNum = null
          item.workblank_scoreInput = null
          item.scoreResult = null
          item.hardcover_scoreResult = null
          item.workblank_scoreResult = null
          item.noCheck = false
          item.isDelete = 0
          item.dicts = item.enumDicts || this.dict.type.cq_eval_abc
        })
        // if (this.query.inputMode === CQ_EVAL_INPUT_MODE.OPTION) {
        //   this.allCheckItemList = options.checkItemList
        //   this.checkItemList = []
        // } else {
        //   this.allCheckItemList = options.checkItemList
        //   this.checkItemList = options.checkItemList
        // }
        options.checkItemList.forEach(item => {
          const itemData = {
            'chkitemScoreId': '',
            'versionId': '9c615756b79d2bfe4174f2657a12aefd',
            'versionCode': '2023052501',
            'chkitemCfgId': '3a52f3d0be0bbd75dd83d9d697e91a56',
            'chkitemCode': 'GC-001-005-001',
            'scoreType': '100',
            'scoreInput': 0,
            'scoreLevel': 'C',
            'scoreResult': 'UNVALID',
            'isValid': 0,
            'isExce': 0
          }
          item.data = JSON.parse(JSON.stringify(itemData))
          item.showThrowTerm = true
        })
        this.allCheckItemList = JSON.parse(JSON.stringify(options.checkItemList))
        this.checkItemList = JSON.parse(JSON.stringify(options.checkItemList))
      }
      if (row) {
        // if (this.query.inputMode === CQ_EVAL_INPUT_MODE.OPTION) {
        //   this.checkItemList = options.checkItemList
        // }
        handleEdit(row)
        this.getRelationScore()
        // this.rdcTypeChange()
      } else {
        this.allNoCheck = true
        this.deliveryChange(self.form.deliveryTypes)
      }
      // this.tradeFilter()
      this.show = true
      this.getPrincipalList()
      /*
      *  集团 关联 集群处理
      * */
      function relationHandle() {
        self.relationObj.scores.forEach(score => {
          if (score.deliveryType === deliveryType.JZMP) {
            score.sort = 1
          } else {
            score.sort = 0
          }
        })
        self.relationObj.scores.sort((obj1, obj2) => {
          if (obj1.sort === obj2.sort) {
            return obj1.chkitemCode.localeCompare(obj2.chkitemCode)
          }
          return obj2.sort - obj1.sort
        })
      }
      // 处理编辑初始化数据
      function handleEdit (row) {
        for (const key in self.form) {
          if (row[key]) {
            if (key === 'constructionId' && row.constructionId) {
              self.form[key] = row[key].split(',')
            } else {
              self.form[key] = row[key]
            }
          }
        }
        self.deliveryChange(self.form.deliveryTypes)
        // 文件
        if (row.sysFiles && row.sysFiles.length > 0) {
          self.fileList = []
          row.sysFiles.forEach(file => {
            self.fileList.push({
              name: file.fileName,
              id: file.id,
              type: file.type
            })
          })
        }
        if (row.scores && row.scores.length > 0) {
          for (let i = 0; i < self.checkItemList.length; i++) {
            for (let j = 0; j < row.scores.length; j++) {
              if (row.scores[j].chkitemCode === self.checkItemList[i].chkitemCode) {
                self.checkItemList[i].noCheck = row.scores[j].scoreResult === CQ_EVAL_RESULT.THROWTERM
                if (self.shareItemCode.some(code => code === self.checkItemList[i].chkitemCode)) {
                  self.checkItemList[i].chkitemScoreId = row.scores[j].chkitemScoreId
                  self.checkItemList[i].scoreNum = row.scores[j].scoreNum
                  self.checkItemList[i].scoreInput = row.scores[j].scoreInput
                  self.checkItemList[i].scoreResult = row.scores[j].scoreResult
                } else {
                  let preStr = ''
                  if (row.scores[j].deliveryType === deliveryType.MP) {
                    preStr = 'workblank'
                  } else if (row.scores[j].deliveryType === deliveryType.JZ) {
                    preStr = 'hardcover'
                  }
                  self.checkItemList[i][preStr + '_chkitemScoreId'] = row.scores[j].chkitemScoreId
                  self.checkItemList[i][preStr + '_scoreNum'] = row.scores[j].scoreNum
                  self.checkItemList[i][preStr + '_scoreInput'] = row.scores[j].scoreInput
                  self.checkItemList[i][preStr + '_scoreResult'] = row.scores[j].scoreResult
                }
              }
            }
          }
          if (self.query.inputMode === CQ_EVAL_INPUT_MODE.OPTION) {
            self.checkItemList = self.checkItemList.filter(item => row.scores.some(score => score.chkitemCode === item.chkitemCode))
          }
        }
      }
    },
    deliveryChange(val) {
      if (val === deliveryType.JZMP) {
        this.colHeight = '140px'
        this.labelWidth = '40px'
        this.label.mp = '毛坯'
        this.label.jz = '精装'
      } else {
        this.colHeight = '90px'
        this.labelWidth = '0'
        this.label.mp = ''
        this.label.jz = ''
      }
    },
    scoreChange(val, item, levelKey) {
      if (val >= 90) {
        item[levelKey] = 'A'
      } else if (val >= 80) {
        item[levelKey] = 'B'
      } else if (val < 80) {
        item[levelKey] = 'C'
      }
      this.forceUpdate()
    },
    onChangeProject() {
      this.changeXmPrincipal()
      // this.rdcTypeChange()
      // this.tradeFilter()
    },
    changeXmPrincipal() {
      // 改变项目时，若有 项目总、项目工程负责人、项目经理，则覆盖现有值
      const { projectId } = this.form
      if (!projectId) return

      const list = this.formProjectOptions
      const data = list.find(i => i.fid === projectId)
      if (!data) return
      if (data.xmzFids) {
        this.form.xmzId = data.xmzFids
        this.form.xmzName = data.xmzName
      }
      if (data.principalIds) {
        this.form.xmPrincipalId = data.principalIds
        this.form.xmPrincipalName = data.principalNames
      }
      if (data.xmjlId) {
        this.form.xmjlId = data.xmjlId
        this.form.xmjlName = data.xmjlName
      }
    },
    /*
    *  校验检查项 是否全部填写
    * */
    getValidate() {
      let validate = true
      if (this.checkItemList.length > 0) {
        this.checkItemList.forEach(item => {
          if (this.shareItemCode.some(code => code === item.chkitemCode)) { // 精装 毛坯 存一起
            if (!item.scoreInput && item.scoreInput !== 0 && item.scoreResult !== CQ_EVAL_RESULT.THROWTERM) {
              validate = false
            }
          } else {
            const types = this.form.deliveryTypes.split(',')
            for (let i = 0; i < types.length; i++) {
              let preStr = ''
              if (types[i] === deliveryType.MP) {
                preStr = 'workblank'
              } else if (types[i] === deliveryType.JZ) {
                preStr = 'hardcover'
              }
              if (!item[preStr + '_scoreInput'] && item[preStr + '_scoreInput'] !== 0 && item[preStr + '_scoreResult'] !== CQ_EVAL_RESULT.THROWTERM) {
                validate = false
              }
            }
          }
        })
      }
      if (!validate) {
        this.$message.warning('检查项，每项必填。')
      }
      return validate
    },
    /** 提交按钮 */
    submitForm(opts) {
      this.$refs.form.validate(valid => {
        if (valid && !this.formLoading) {
          this.formLoading = true
          this.form.fileIds = []
          this.fileList.forEach(file => {
            this.form.fileIds.push(file.id)
          })
          const params = { ...this.form }
          params.constructionId = params.constructionId.join(',')
          if (opts?.isRepeatEntry) params.isRepeatEntry = opts.isRepeatEntry

          const scores = []
          const types = this.form.deliveryTypes.split(',')
          // 删除项 逻辑删除 isDelete: 1
          const list = [...this.checkItemList]
          if (this.form.prjchkId) { // 新增时不传删除项
            this.removeItemList.forEach(item => {
              if (!list.some(listItem => listItem.chkitemCode === item.chkitemCode)) {
                list.push(item)
              }
            })
          }
          if (list && list.length < 1) {
            this.$message.info('请添加检查项')
            return
          }
          if (types.length > 0) {
            list.forEach(item => {
              if (this.shareItemCode.some(code => code === item.chkitemCode)) {
                scores.push({
                  chkitemCfgId: item.cfgId,
                  chkitemScoreId: item.chkitemScoreId,
                  versionCode: item.itemVersionCode,
                  scoreNum: item.scoreNum,
                  scoreInput: item.scoreInput,
                  scoreResult: item.scoreResult,
                  scoreType: item.scoreType,
                  dataType: item.dataType,
                  deliveryType: this.form.deliveryTypes,
                  chkitemCode: item.chkitemCode,
                  isDelete: item.isDelete
                })
              } else {
                for (let i = 0; i < types.length; i++) {
                  let preStr = ''
                  if (types[i] === deliveryType.MP) {
                    preStr = 'workblank'
                  } else if (types[i] === deliveryType.JZ) {
                    preStr = 'hardcover'
                  }
                  scores.push({
                    chkitemCfgId: item.cfgId,
                    versionCode: item.itemVersionCode,
                    chkitemScoreId: item[preStr + '_chkitemScoreId'],
                    scoreNum: item[preStr + '_scoreNum'],
                    scoreInput: item[preStr + '_scoreInput'],
                    scoreResult: item[preStr + '_scoreResult'],
                    scoreType: item.scoreType,
                    dataType: item.dataType,
                    deliveryType: types[i],
                    chkitemCode: item.chkitemCode,
                    isDelete: item.isDelete
                  })
                }
              }
            })
          }
          params.scores = scores
          const validate = scores.every(item => (item.scoreInput || item.scoreInput === 0) || item.scoreResult === CQ_EVAL_RESULT.THROWTERM)
          if (!validate) {
            this.formLoading = false
            this.$message({message: '检查项，每项都必填。', type: 'warning', offset: 400})
            return
          }
          saveScores(params).then(response => {
            if (response.code === 200) {
              // 已有相似的数据
              if (response.data?.isRepeatEntry === 'duplicate') {
                const opt = { checkItemList: this.checkItemList, data: response.data }
                return this.$refs.SimilarDataConfirm.open(opt)
              }

              const msg = this.form.prjchkId ? '编辑成功' : '新增成功'
              this.msgSuccess(msg)
              this.close()
            }
            this.$emit('ok')
          }).finally(() => {
            this.formLoading = false
          })
        }
      })
    },
    close () {
      this.$refs.form.resetFields()
      this.show = false
      this.allNoCheck = false
    },
    // 图片上传相关方法
    beforeUpload(file) {
      const isOk = file.size > 0
      // const isAccept = acceptTypeList.includes(file.type)
      // const isLt10M = file.size / 1024 / 1024 < 10
      // if (!isAccept) this.msgError('上传图片只能是 JPG/PNG 格式!')
      if (!isOk) this.$message.warning('上传文件不能为空')
      if (!this.uploading) this.uploading = isOk
      return isOk
    },
    onUploadError(err, file, fileList) {
      this.uploading = false
      this.msgError(`上传失败 ${err?.msg || ''}`)
    },
    async onUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)
      this.uploading = false
      if (res.code !== 200) {
        return this.msgError(`上传失败 ${res.msg || ''}`)
      } else {
        this.fileList.push({
          id: res.data[0],
          name: file.name
        })
      }
    },
    onPreview(fileObj) {
      console.log(fileObj)
      this.fileLoading = true
      // window.open(getFileURL(fileObj.name))
      downloadFile(fileObj.id).then(file => {
        var elink = document.createElement('a')
        var blob = new Blob([file])
        elink.download = fileObj.name
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        elink.click()
      }).finally(() => {
        this.fileLoading = false
      })
    },
    async handleRemove(file) {
      const res1 = await this.$confirm('确定删除此文件?', '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      // 从列表移除
      const index = this.fileList.findIndex(i => i.id === file.id)
      if (index > -1) {
        this.fileList.splice(index, 1)
        this.msgSuccess('删除成功')
      }
    }
  }
}
</script>
<style scoped lang="scss">
  .optimized-select {
    width: 100%;
    & /deep/.el-select__tags {
      white-space: nowrap;
      overflow: hidden;
      flex-wrap: nowrap;
      .el-tag--info {
        max-width: 70%;
      }
    }
  }
  .opt-list-wrap {
    margin: 0 -12px;
    .opt-list {
      max-height: 300px;
      overflow-y: auto;
    }
    .opt-item {
      font-size: 12px;
      padding: 0 40px 0 20px;
      color: #606266;
      line-height: 34px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
      }
    }
    .selected {
      color: #409eff;
      font-weight: 700;
      &::after {
        position: absolute;
        right: 20px;
        font-family: 'element-icons';
        content: '\e6da';
        font-size: 12px;
      }
    }
    .disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    .btn {
      text-align: right;
      padding: 10px 20px 0;
    }
  }
  .relation-prochk {
    padding-top: 20px;
    display: flex;
    flex-wrap: wrap;
    .score-wrap {
      display: flex;
      flex-wrap: wrap;
    }
    .row-score,
    .row {
      width: 300px;
      padding-bottom: 10px;
      span:nth-child(1) {
        display: inline-block;
        width: 80px;
        text-align: right;
        margin-right: 10px;
      }
      .value,
      span:nth-child(2) {
        display: inline-block;
        min-width: 80px;
        font-weight: bold;
        background-color: #eff2f9;
        padding: 0 10px;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
        vertical-align: middle;
      }
      span:nth-child(3) {
        margin-left: 10px;
      }
    }
  }
  .row-score {
    display: flex;
    align-items: center;
    .delivery-type {
      font-size: 12px;
      color: #99a9bf;
    }
  }
  .form-score {
    margin: -20px -20px 0 0;
    padding-right: 20px;
    height: calc(95vh - 200px);
    overflow-y: auto;
  }
  .operate-btn {
    text-align: end;
    margin: 10px 20px -10px 0;
  }
  .file-list {
    .file-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      margin-top: 10px;
      border-radius: 5px;
      border: 1px solid #d2e8ff;
      .file-name {
        cursor: pointer;
        display: flex;
        align-items: center;
        .name {
          margin: 0 10px;
          line-height: 20px;
        }
        &:hover {
          color: #409EFF;
        }
        .el-icon-document {
          font-size: 16px;
        }
      }
      .el-icon-close {
        cursor: pointer;
        &:hover {
          color: #409EFF;
        }
      }
    }
  }
  .input-width {
    width: 100%;
  }
  .score-title {
    text-align: center;
    background-color: #f0f9eb;
    border:1px solid #e1f3d8;
    color: #67c23a;
    height: 36px;
    line-height: 36px;
    margin: 0 0 10px 0px;
    border-radius: 5px;
  }
  .mode-option {
    display: flex;
    margin-bottom: 10px;
  }
  .item {
    border-radius: 5px;
   /* border:1px solid #d9ecff;
    background-color: #ecf5ff;*/
    box-shadow: 0 2px 12px 0 rgba(black, 0.1);
    margin-bottom: 10px;
    padding-left: 20px;
    .lable-title {
     /* color: #7b7b7b;
      text-align: left;
      margin-left: 4px;
      height: 40px;
      line-height: 40px;*/
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ebeef5;
      padding: 10px 10px 5px;
      margin:0 0 10px -20px;
      .btn-remove {
        padding: 3px;
        &:hover {
          color: #409eff;
        }
      }
    }
    .custom-form-item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
      .label-select {
        display: flex;
        align-items: center;
      }
      .score-result {
        cursor: pointer;
        margin-right: 20px;
      }
    }
    .score-value,
    .score-level {
      width: 100px;
    }
  }
  .list {
    display: flex;
    flex-wrap: wrap;
  }
  .item {
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(black, 0.1);
    margin: 0 20px 20px 0;
  }
</style>
<style lang="scss">
  .EXCELLENT {
    color: #67c23a;
  }
  .VALID {
    color: #409eff;
  }
  .UNVALID {
    color: #f56c6c;
  }
  .relation-item {
    margin-left: 20px;
    cursor: pointer;
    &:hover {
      color: #409EFF;
    }
  }
</style>
